package com.hbnu.util;

import com.ruoyi.common.core.domain.R;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class DrawCode {
//    public static void main(String[] args) {
//        drawCode();
//    }
    static String[] strings = {"2", "3", "4", "5", "6", "7", "8", "9",
            "a", "b", "c", "d", "e", "f", "g", "h",  "j", "k", "m",
            "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G", "H", "J","K","M","N","P",
            "Q","R","S","T","U","V","W","X","Y","Z"};
    public static Map<String, String> drawCode() {
        BufferedImage image = new BufferedImage(62, 40, BufferedImage.TYPE_INT_RGB);//图片采用的三原色
        Graphics g = image.getGraphics();
        g.setFont(new Font("微软雅黑", Font.BOLD, 20));
        Random random = new Random();
        g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
        g.fillRect(0, 0, 62, 40);
        g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
        int x = -10;
        String code = "";
        for (int i = 0; i < 4; i++) {
            String str = strings[random.nextInt(strings.length)];
            code += str;
            g.drawString(str, x += 15, 15);
        }
        g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
        for (int i = 0; i < 2; i++) {
            int x1 = random.nextInt(10);
            int y1 = random.nextInt(40);
            int x2 = random.nextInt(10) + 50;
            int y2 = random.nextInt(40);
            g.drawLine(x1, y1, x2, y2);
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String base64Image = null;
//        try {
//            ImageIO.write(image, "png", new File("D:\\code.png"));
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        System.out.println(code);
        try {
            ImageIO.write(image, "png", bos);
            byte[] imageBytes = bos.toByteArray();
            String base64String = Base64.getEncoder().encodeToString(imageBytes);
            // 返回给前端（通常包装一下）
            base64Image = "data:image/png;base64," + base64String;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", code);
        resultMap.put("image", base64Image);
        return resultMap;
    }
}
